package com.zzw.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.springboot.common.Constants;
import com.zzw.springboot.common.ErrorResult;
import com.zzw.springboot.controller.dto.UserDto;
import com.zzw.springboot.controller.dto.UserPasswordDTO;
import com.zzw.springboot.entity.Course;
import com.zzw.springboot.entity.Menu;
import com.zzw.springboot.entity.User;
import com.zzw.springboot.exception.BusinessException;
import com.zzw.springboot.mapper.RoleMapper;
import com.zzw.springboot.mapper.RoleMenuMapper;
import com.zzw.springboot.mapper.UserMapper;
import com.zzw.springboot.service.ICourseService;
import com.zzw.springboot.service.IMenuService;
import com.zzw.springboot.service.IUserService;
import com.zzw.springboot.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzw2000
 * @since 2022-05-10 22:11:15
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     *
     * @param userDto
     * @return
     */
    @Override
    public UserDto login(UserDto userDto) {
        String password = DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes());
        User user;
        try {
            user = getOne(Wrappers.<User>lambdaQuery()
                    .eq(User::getUsername, userDto.getUsername())
                    .eq(User::getPassword, password));

        } catch (Exception e) {
            log.error("登录时出现的错误：数据库中出现了重名的现象" + e.getMessage());
            throw new BusinessException(ErrorResult.serverError());
        }
        if (Objects.nonNull(user)) {
            BeanUtil.copyProperties(user, userDto, true);
            //设置token
            userDto.setToken(JwtUtils.generateToken(user.getId().toString(), user.getPassword()));

            String role = user.getRole();
            //设置用户菜单列表
            userDto.setMenus(getRoleMenus(role));
            return userDto;
        } else {
            throw new BusinessException(ErrorResult.loginError());
        }
    }

    /**
     * 用户注册
     *
     * @param userDto
     */
    @Override
    public User register(UserDto userDto) {
        User one = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, userDto.getUsername()));
        if (Objects.nonNull(one)) {
            throw new BusinessException(ErrorResult.repeatRegister());
        }
        User user = new User();
        BeanUtil.copyProperties(userDto, user, true);
        //对密码进行md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        save(user);
        return user;
    }

    /**
     * 修改密码
     *
     * @param userPasswordDTO
     */
    @Override
    public void updatePwd(UserPasswordDTO userPasswordDTO) {
        userPasswordDTO.setPassword(DigestUtils.md5DigestAsHex(userPasswordDTO.getPassword().getBytes()));
        userPasswordDTO.setNewPassword(DigestUtils.md5DigestAsHex(userPasswordDTO.getNewPassword().getBytes()));
        int row = userMapper.updatePwd(userPasswordDTO);
        if (row < 1) {
            throw new BusinessException(ErrorResult.errorPwd());
        }
    }

    /**
     * 分页查询
     *
     * @param userPage
     * @param username
     * @param email
     * @param address
     * @return
     */
    @Override
    public Page<User> findPage(Page<User> userPage, String username, String email, String address) {
        Page<User> usersPage = page(userPage, Wrappers.<User>lambdaQuery()
                .like(StringUtils.isNotEmpty(username), User::getUsername, username)
                .like(StringUtils.isNotEmpty(email), User::getEmail, email)
                .like(StringUtils.isNotEmpty(address), User::getAddress, address)
                .orderByDesc(User::getRole)
                .orderByDesc(User::getCreateTime));
        List<User> users = usersPage.getRecords().stream().peek(user -> {
            if (Objects.equals(user.getRole(), Constants.ROLE_TEACHER)) {
                List<Course> courses = courseService.list(Wrappers.<Course>lambdaQuery()
                        .eq(Course::getTeacherId, user.getId()));
                user.setCourses(courses);
            }
        }).collect(Collectors.toList());
        usersPage.setRecords(users);
        return usersPage;
    }

    /**
     * 获取当前用户角色菜单列表
     *
     * @param role
     * @return
     */
    private List<Menu> getRoleMenus(String role) {
        Integer roleId = roleMapper.selectByFlag(role);
        //当前角色所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);
        //查出系统中所有菜单
        List<Menu> menus = menuService.findMenus("");
        //筛选当前用户角色菜单
        List<Menu> roleMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            //移除children中不在menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
